package cn.net.scp.test.app;


public class LeetCode92 {

    public static void main(String[] args) {

        LeetCode92 leetCode92 = new LeetCode92();

        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

//        ListNode l = leetCode92.reverse(head);
//
//        System.out.println("---");
//        while (l != null) {
//            System.out.print(l.val + "->");
//            l = l.next;
//        }
//        System.out.println();

        System.out.println("---");

        ListNode l2 = leetCode92.reverseBetween(head, 2, 4);
        while (l2 != null) {
            System.out.print(l2.val + "->");
            l2 = l2.next;
        }
        System.out.println();


    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        if (head == null) {
            return null;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;

        int i = 0;
        ListNode prev = dummy;
        while (i < left) {
            prev = prev.next;
            i++;
        }



        // 创建变量
        ListNode preN = prev.next;

        ListNode pre = prev.next;
        ListNode curr = pre.next;
        pre.next = null;

        //  a -> b -> c -> d -> e
        //  a -> b -> d -> c -> e

        // 开始反转区间
        while (i < right && curr!= null) {
            ListNode tmp = curr.next;
            curr.next = pre;
            pre = curr;
            curr = tmp;
            i++;
        }

        prev.next = pre;
        preN.next = curr;
        return dummy.next;
    }

    public ListNode reverse(ListNode head) {
        if (head == null) {
            return null;
        }

        ListNode pre, curr;

        curr = head.next;
        pre = head;
        pre.next = null;

        while (curr != null) {
            ListNode tmp = curr.next;
            curr.next = pre;
            pre = curr;
            curr = tmp;
        }

        return pre;
    }

}

class ListNode {

    public int val;
    public ListNode next;

    ListNode(int x) {
        val = x;
    }
}
